package me.drakeet.meizhi.ui;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.drakeet.meizhi.R;
import me.drakeet.meizhi.ui.base.BaseActivity;
import me.drakeet.meizhi.util.RxMeizhi;
import me.drakeet.meizhi.util.Shares;
import me.drakeet.meizhi.util.Toasts;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import uk.co.senab.photoview.PhotoViewAttacher;


/**
 * Created by ThinkPad on 2017/4/12.
 */

public class PictureActivity1 extends BaseActivity {
    private static final String TAG = "PictureActivity1";
    public static final String TRANSIT_PIC = "picture";
    public static final String EXTRA_IMAGE_URL = "image_url";
    public static final String EXTRA_IMAGE_TITLE = "image_title";
    @Bind(R.id.iv_tool_bar_pic)
    ImageView ivToolBarPic;
    @Bind(R.id.main_ll_title_container)
    LinearLayout mainLlTitleContainer;
    @Bind(R.id.fl_title)
    FrameLayout flTitle;
    @Bind(R.id.ly_pic_app_bar)
    AppBarLayout lyPicAppBar;
    @Bind(R.id.tv_tool_bar_info)
    TextView tvToolBarInfo;
    PhotoViewAttacher mPhotoViewAttacher;
    @Bind(R.id.toolbar)
    Toolbar toolbar;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture1);

        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        parseIntent();
        ViewCompat.setTransitionName(ivToolBarPic, TRANSIT_PIC);
        Picasso.with(this).load(mImageUrl).into(ivToolBarPic);
        setTitle(mImageTitle);
        tvToolBarInfo.setText(mImageTitle);
        setupPhotoAttacher();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_picture, menu);
        // TODO: 把图片的一些信息，比如 who，加载到 Overflow 当中
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_share:
                RxMeizhi.saveImageAndGetPathObservable(this, mImageUrl, mImageTitle)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(uri -> Shares.shareImage(this, uri,
                                getString(R.string.share_meizhi_to)),
                                error -> Toasts.showLong(error.getMessage()));
                return true;
            case R.id.action_save:
                saveImageToGallery();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }


    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    private String mImageUrl;
    private String mImageTitle;

    private void parseIntent() {
        mImageUrl = getIntent().getStringExtra(EXTRA_IMAGE_URL);
        mImageTitle = getIntent().getStringExtra(EXTRA_IMAGE_TITLE);
    }

    public static Intent newIntent(Context context, String url, String desc) {
        Intent intent = new Intent(context, PictureActivity1.class);
        Log.d(TAG, "EXTRA_IMAGE_URL" + url);
        Log.d(TAG, "EXTRA_IMAGE_TITLE " + desc);
        intent.putExtra(PictureActivity1.EXTRA_IMAGE_URL, url);
        intent.putExtra(PictureActivity1.EXTRA_IMAGE_TITLE, desc);
        return intent;
    }

    private void setupPhotoAttacher() {
        mPhotoViewAttacher = new PhotoViewAttacher(ivToolBarPic);
        // mPhotoViewAttacher.setOnViewTapListener((view, v, v1) -> hideOrShowToolbar());
        // @formatter:off
        mPhotoViewAttacher.setOnLongClickListener(v -> {
            new AlertDialog.Builder(PictureActivity1.this)
                    .setMessage(getString(R.string.ask_saving_picture))
                    .setNegativeButton(android.R.string.cancel,
                            (dialog, which) -> dialog.dismiss())
                    .setPositiveButton(android.R.string.ok,
                            (dialog, which) -> {
                                saveImageToGallery();
                                dialog.dismiss();
                            })
                    .show();
            // @formatter:on
            return true;
        });
    }


    private void saveImageToGallery() {
        // @formatter:off
        Subscription s = RxMeizhi.saveImageAndGetPathObservable(this, mImageUrl, mImageTitle)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(uri -> {
                    File appDir = new File(Environment.getExternalStorageDirectory(), "Meizhi");
                    String msg = String.format(getString(R.string.picture_has_save_to),
                            appDir.getAbsolutePath());
                    Toasts.showShort(msg);
                }, error -> Toasts.showLong(error.getMessage() + "\n再试试..."));
        // @formatter:on
        addSubscription(s);
    }
}
